package com.hogan.hoganproject.home.mvp;


import com.hogan.hoganproject.base.rx.ErrorBean;
import com.hogan.hoganproject.base.rx.ResultConsumer;
import com.hogan.hoganproject.base.rx.SchedulersCompat;
import com.hogan.hoganproject.base.utils.LogUtil;
import com.hogan.hoganproject.home.api.HomeApi;
import com.hogan.hoganproject.home.api.JuHeBean;

import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


/**
 * Author: chenhu
 * Time: 2020/8/31 10:11
 * Description do somethings
 */
public class HomePresenter extends HomeControl.HPresenter<HomeControl.HomeView> {
    private HomeApi mHomeApi;

    public HomePresenter() {
        mHomeApi = mBaseRetrofit.create(HomeApi.class);
    }

    @Override
    public void getNewsData(Map<String, String> map) {
        mHomeApi.getTopNewData(map)
                .compose(SchedulersCompat.applyIoSchedulers())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mView != null) {
                            mView.showDialog();
                        }
                    }
                })
                .doAfterTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        if (mView != null) {
                            mView.disDialog();
                        }
                    }
                })
                .subscribe(new ResultConsumer() {
                    @Override
                    public void onError(ErrorBean errorBean) {
                        if (mView != null) {
                            mView.onLoadDataFail(errorBean.getErrMessage());
                            stopRefreshOrLoadMoreData();
                        }
                    }

                    @Override
                    public void onData(Object object) {
                        JuHeBean.ResultBean bean = (JuHeBean.ResultBean) object;
                        if (bean != null && bean.getData() != null) {
                            if (mView != null) {
                                mView.updateNewsData(bean);
                                stopRefreshOrLoadMoreData();
                            }
                        } else {
                            if (mView != null) {
                                mView.onLoadDataFail("数据为空");
                                stopRefreshOrLoadMoreData();
                            }
                        }
                    }
                });
    }

    private void stopRefreshOrLoadMoreData() {
        if (mView != null) {
            mView.stopRefreshData();
            mView.stopLoadMoreData();
        }
    }
}
